//
//  MGAlertManager.m
//  MoneyRecord_iOS
//
//  Created by alchemy on 2022/2/12.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGAlertManager.h"

@implementation MGAlertManager

+ (void)createAlert:(MGRecordModel *)recordModel completeBlock:(YYBTapedActionBlock)completeBlock {
    NSString *uniqueID = @(recordModel.uniqueId).stringValue;
    
    [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[uniqueID]];
    
    UNNotificationTrigger *trigger;
    NSDate *alertDate = recordModel.alertModel.startDate;
    MGAlertType type = recordModel.alertModel.type;
    
    switch (type) {
        case MGAlertTypeDay: {
            NSDateComponents *compos = [NSDateComponents new];
            compos.hour = alertDate.components.hour;
            compos.minute = alertDate.components.minute;
            compos.second = 0;
            trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:compos repeats:YES];
        }
            break;
        default:
            break;
    }
    
    if (trigger) {
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.title = @"小助理提醒您";
        content.body = recordModel.alertModel.content;
        
        MGAlertSoundModel *alertSoundModel = recordModel.alertModel.soundModel;
    
        NSString *soundName = [alertSoundModel.soundFileName stringByAppendingString:@".mp3"];
        UNNotificationSound *sound = [UNNotificationSound soundNamed:soundName];
        content.sound = sound;
        
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:uniqueID content:content trigger:trigger];
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completeBlock) {
                    completeBlock();
                }
            });
        }];
    } else {
        if (completeBlock) {
            completeBlock();
        }
    }
}

+ (void)deleteAlert:(MGRecordModel *)recordModel {
    NSString *uniqueID = @(recordModel.uniqueId).stringValue;
    [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[uniqueID]];
}

+ (void)startNotification {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self refreshAllAlerts];
        });
    }];
}

+ (void)refreshAllAlerts {
    NSArray *recordModels = MGRecordAccessor.shared.dataModels;
    for (MGRecordModel *dataModel in recordModels) {
        [self createAlert:dataModel completeBlock:nil];
    }
}

@end
